package com.ycsj.common.http;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.Map;

/**
 * 请求的具体执行者,代理模式中真正工作的角色
 * Created by Administrator on 2018/12/6 0006.
 */

public class OkGoProcessor implements IHttpProcessor {
    @Override
    public void post(String url, Map<String, String> params, final ICallBack callBack) {
        OkGo.<String>post(url).params(params).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (null != callBack) {
                    callBack.onSuccess(response.body());
                }
            }

            @Override
            public void onError(Response<String> response) {
                if (null != callBack) {
                    callBack.onError(response.body());
                }
            }

            /**
             * 如果希望OkGo框架只在请求状态为200的时候走onSuccess()方法,其它返回码都走onError()，
             * 必须重写convertResponse()方法,针对非200响应码的情况做抛异常处理
             * @param response
             * @return
             * @throws Throwable
             */
            @Override
            public String convertResponse(okhttp3.Response response) throws Throwable {
                if (!response.isSuccessful()) {
                    //对于响应code不为200的情况均认为是服务器异常的方法
                    throw new IllegalStateException(response.code() + "");
                }
                return super.convertResponse(response);
            }
        });
    }

    @Override
    public void get(String url, Map<String, String> params, final ICallBack callBack) {
        OkGo.<String>get(url).params(params).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (null != callBack) {
                    callBack.onSuccess(response.body());
                }
            }

            @Override
            public void onError(Response<String> response) {
                if (null != callBack) {
                    callBack.onError(response.body());
                }
            }
        });
    }
}
